/**
 * JAVACC DEMO 1.0
 * @copy right dwusoft company All rights reserved. 
 * @Package com.dwusoft.message.service.helper  
 */
package com.dwusoft.platform.template;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;

import net.sf.json.util.JSONUtils;

import org.apache.log4j.Logger;

import com.apache.database.constant.SystemTools;
import com.apache.uct.common.ToolsUtil;
import com.dwusoft.platform.template.method.FormatDateMethod;
import com.dwusoft.platform.template.method.FormatPriceMethod;
import com.dwusoft.platform.template.method.StringNullMethod;
import com.dwusoft.platform.template.method.SubStringMethod;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * description:  模板操作辅助类
 * @author Hou Dayu 创建时间：2015-7-8  
 * @Copyright(c)2014:北京软件技术有限公司
 */
public class FreemarkerHelper {

	private Logger log = Logger.getLogger(FreemarkerHelper.class);
	private static FreemarkerHelper helper;

	private Configuration freemarker_cfg = null;

	private FreemarkerHelper() {
	}

	public static FreemarkerHelper instance() {
		if (null == helper) {
			helper = new FreemarkerHelper();
		}
		return helper;
	}

	public String getTemplateStr(String templateName, Map mapData) throws Exception {
		Template template = getFreeMarkerCFG().getTemplate(templateName);
		template.setEncoding("UTF-8");

		StringWriter stream = new StringWriter();
		template.process(mapData, stream);
		String sndRtn = stream.toString();//FreeMarkerTemplateUtils.processTemplateIntoString(template, mapData);
		return sndRtn;
	}

	/**
	 * 生成静态页面的方法
	 * 
	 * @param context  上下文路径(必须为绝对路径：如D:/)
	 * @param data     装载数据的结果集
	 * @param tempName ftl模板文件路径及名称(此变量加上context为一个完整的绝对路径 如：D:/index.ftl)
	 * @param htmlPath 生成静态页面的路径及名称(必须为绝对路径：如D:/index.html)
	 */
	public boolean createHtml(String ftlPath, Map<String, Object> data, String htmlPath) {
		if (ToolsUtil.isNull(ftlPath) || ToolsUtil.isNull(htmlPath))
			return false;
		Writer out = null;
		htmlPath = FileOperateUtil.getFormatFilePath(htmlPath);
		String hPath = htmlPath.substring(0, htmlPath.lastIndexOf("/") + 1);
		log.info("ftlPath="+ftlPath);
		try {
			//指定模板路径//
			Template template = getFreeMarkerCFG().getTemplate(ftlPath);
			if (template == null)
				return false;
			log.info("hPath="+hPath);
			FileOperateUtil.newCreateFolder(hPath);
			File htmlFile = new File(htmlPath);
			out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile), "UTF-8"));
			template.process(data, out); //处理模板
			out.flush();
		} catch (Exception e) {
			log.error(e.getMessage());
			return false;
		} finally {
			try {
				if (out != null)
					out.close();
			} catch (Exception e) {
				log.error(e.getMessage());
			}
		}
		return true;
	}

	/** 
	 * 获取freemarker的配置. freemarker本身支持classpath,目录和从ServletContext获取. 
	 */
	private Configuration getFreeMarkerCFG() {
		if (null == freemarker_cfg) {
			File templateFile = new File(SystemTools.getInstance().getValue("template_path"));
			log.info("templateFile="+templateFile.getPath());
			freemarker_cfg = new Configuration();
			try {
				freemarker_cfg.setDirectoryForTemplateLoading(templateFile);
				freemarker_cfg.setEncoding(Locale.CHINA, "UTF-8");
			} catch (IOException e) {
				log.error("Get tempalte error", e);
			}
			freemarker_cfg.setSharedVariable("timeStr", new FormatDateMethod());
			freemarker_cfg.setSharedVariable("priceStr", new FormatPriceMethod());
			freemarker_cfg.setSharedVariable("subString", new SubStringMethod());
			freemarker_cfg.setSharedVariable("str", new StringNullMethod());
		}
		return freemarker_cfg;
	}
}
